// 结果页面脚本
document.addEventListener('DOMContentLoaded', function() {
    // 从localStorage获取结果数据
    loadFortuneResult();
    
    // 添加动画效果
    addAnimationEffects();
    
    // 处理浏览器后退按钮
    handleBrowserNavigation();
});

// 处理浏览器导航
function handleBrowserNavigation() {
    // 添加历史记录状态
    if (!window.history.state) {
        window.history.replaceState({ page: 'result' }, '算命结果', 'result.html');
    }
    
    // 监听后退按钮
    window.addEventListener('popstate', function(event) {
        // 如果用户点击后退，清除数据并返回首页
        localStorage.removeItem('fortuneResult');
        window.location.href = 'index.html';
    });
}

// 加载算命结果
function loadFortuneResult() {
    try {
        // 首先尝试从URL参数获取数据
        const urlData = getDataFromURL();
        if (urlData) {
            displayFortuneResult(urlData);
            return;
        }
        
        // 然后尝试从localStorage获取数据
        const fortuneData = localStorage.getItem('fortuneResult');
        
        if (!fortuneData) {
            // 如果没有数据，显示错误并返回首页
            showNoDataError();
            return;
        }
        
        const data = JSON.parse(fortuneData);
        
        // 验证数据完整性
        if (!validateFortuneData(data)) {
            showDataError();
            return;
        }
        
        // 显示结果数据
        displayFortuneResult(data);
        
    } catch (error) {
        console.error('加载算命结果错误:', error);
        showDataError();
    }
}

// 从URL参数获取数据
function getDataFromURL() {
    try {
        const urlParams = new URLSearchParams(window.location.search);
        const encodedData = urlParams.get('data');
        
        if (encodedData) {
            const decodedData = decodeURIComponent(encodedData);
            const data = JSON.parse(decodedData);
            
            if (validateFortuneData(data)) {
                return data;
            }
        }
        
        return null;
    } catch (error) {
        console.error('URL参数解析错误:', error);
        return null;
    }
}

// 验证算命数据完整性
function validateFortuneData(data) {
    return data && 
           data.userInfo && 
           data.userInfo.name && 
           data.userInfo.birthDate && 
           data.userInfo.gender &&
           data.zodiac && 
           data.constellation && 
           data.fortune && 
           data.fortune.today && 
           typeof data.fortune.luckyNumber === 'number' && 
           data.fortune.luckyColor;
}

// 显示算命结果
function displayFortuneResult(data) {
    // 显示用户信息
    displayUserInfo(data.userInfo);
    
    // 显示生肖星座
    displayZodiacInfo(data.zodiac, data.constellation);
    
    // 显示运势
    displayFortune(data.fortune);
    
    // 显示天气信息（如果有）
    if (data.fortune.weather) {
        displayWeatherInfo(data.fortune.weather);
    }
    
    // 添加渐入动画
    animateCards();
}

// 显示用户信息
function displayUserInfo(userInfo) {
    document.getElementById('userName').textContent = userInfo.name;
    document.getElementById('userBirthDate').textContent = formatDate(userInfo.birthDate);
    document.getElementById('userGender').textContent = formatGender(userInfo.gender);
    document.getElementById('userCity').textContent = userInfo.city || '当前位置';
}

// 显示生肖星座信息
function displayZodiacInfo(zodiac, constellation) {
    document.getElementById('zodiac').textContent = zodiac;
    document.getElementById('constellation').textContent = constellation;
}

// 显示运势信息
function displayFortune(fortune) {
    document.getElementById('fortuneText').textContent = fortune.today;
    document.getElementById('luckyNumber').textContent = fortune.luckyNumber;
    
    const luckyColorElement = document.getElementById('luckyColor');
    luckyColorElement.textContent = fortune.luckyColor;
    
    // 为幸运颜色添加颜色显示
    addColorIndicator(luckyColorElement, fortune.luckyColor);
}

// 格式化日期显示
function formatDate(dateString) {
    try {
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        
        return `${year}年${month}月${day}日`;
    } catch (error) {
        return dateString;
    }
}

// 格式化性别显示
function formatGender(gender) {
    return gender === 'male' ? '男' : '女';
}

// 为幸运颜色添加颜色指示器
function addColorIndicator(element, colorName) {
    // 颜色映射表
    const colorMap = {
        '红色': '#ff4757',
        '橙色': '#ff6348',
        '黄色': '#ffdd59',
        '绿色': '#2ed573',
        '蓝色': '#3742fa',
        '紫色': '#8c7ae6',
        '粉色': '#ff6b9d',
        '白色': '#ffffff',
        '黑色': '#2f3542',
        '灰色': '#747d8c',
        '金色': '#ffd700',
        '银色': '#c0c0c0'
    };
    
    const colorCode = colorMap[colorName] || '#667eea';
    
    // 创建颜色指示器
    const colorIndicator = document.createElement('span');
    colorIndicator.className = 'color-indicator';
    colorIndicator.style.cssText = `
        display: inline-block;
        width: 20px;
        height: 20px;
        background-color: ${colorCode};
        border-radius: 50%;
        margin-left: 8px;
        vertical-align: middle;
        border: 2px solid #fff;
        box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    `;
    
    // 特殊处理白色，添加边框
    if (colorName === '白色') {
        colorIndicator.style.border = '2px solid #ddd';
    }
    
    element.appendChild(colorIndicator);
}

// 显示天气信息
function displayWeatherInfo(weather) {
    const weatherCard = document.getElementById('weatherCard');
    if (!weatherCard) return;
    
    // 显示天气卡片
    weatherCard.style.display = 'block';
    
    // 显示主要天气信息
    document.getElementById('weatherTemp').textContent = `${weather.temperature}°C`;
    document.getElementById('weatherDesc').textContent = weather.weather;
    
    // 显示温度范围
    document.getElementById('weatherTempRange').textContent = 
        `${weather.temperatureLow}°C ~ ${weather.temperatureHigh}°C`;
    
    // 显示风力风向
    document.getElementById('weatherWind').textContent = 
        `${weather.wind} ${weather.windSpeed}`;
    
    // 显示空气质量
    const airQuality = weather.airQuality;
    const airQualityText = getAirQualityText(airQuality);
    document.getElementById('weatherAir').innerHTML = 
        `${airQuality} <span style="color: ${getAirQualityColor(airQuality)}">(${airQualityText})</span>`;
    
    // 显示湿度
    document.getElementById('weatherHumidity').textContent = weather.humidity;
    
    // 显示更新时间
    document.getElementById('weatherUpdate').textContent = 
        `${weather.date} ${weather.updateTime}`;
}

// 获取空气质量描述
function getAirQualityText(aqi) {
    const aqiValue = parseInt(aqi);
    if (aqiValue <= 50) return '优';
    if (aqiValue <= 100) return '良';
    if (aqiValue <= 150) return '轻度污染';
    if (aqiValue <= 200) return '中度污染';
    if (aqiValue <= 300) return '重度污染';
    return '严重污染';
}

// 获取空气质量颜色
function getAirQualityColor(aqi) {
    const aqiValue = parseInt(aqi);
    if (aqiValue <= 50) return '#00e400';
    if (aqiValue <= 100) return '#ffff00';
    if (aqiValue <= 150) return '#ff7e00';
    if (aqiValue <= 200) return '#ff0000';
    if (aqiValue <= 300) return '#8f3f97';
    return '#7e0023';
}

// 添加动画效果
function addAnimationEffects() {
    // 为卡片添加CSS动画类
    const style = document.createElement('style');
    style.textContent = `
        .card-animate {
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.6s ease;
        }
        
        .card-animate.show {
            opacity: 1;
            transform: translateY(0);
        }
        
        .fade-in {
            animation: fadeIn 0.8s ease-in-out;
        }
        
        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: scale(0.95);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
        
        .number-animate {
            display: inline-block;
            animation: bounce 0.6s ease-in-out;
        }
        
        @keyframes bounce {
            0%, 20%, 50%, 80%, 100% {
                transform: translateY(0);
            }
            40% {
                transform: translateY(-10px);
            }
            60% {
                transform: translateY(-5px);
            }
        }
    `;
    document.head.appendChild(style);
}

// 卡片动画
function animateCards() {
    const cards = document.querySelectorAll('.user-info-card, .fortune-card, .lucky-card, .weather-card');
    
    cards.forEach((card, index) => {
        card.classList.add('card-animate');
        
        setTimeout(() => {
            card.classList.add('show');
        }, index * 200);
    });
    
    // 为幸运数字添加特殊动画
    setTimeout(() => {
        const luckyNumber = document.getElementById('luckyNumber');
        if (luckyNumber) {
            luckyNumber.classList.add('number-animate');
        }
    }, 1000);
}

// 显示无数据错误
function showNoDataError() {
    showErrorMessage('没有找到算命结果，请重新进行算命', true);
}

// 显示数据错误
function showDataError() {
    showErrorMessage('算命结果数据异常，请重新进行算命', true);
}

// 显示错误消息
function showErrorMessage(message, redirectToHome = false) {
    const container = document.querySelector('.result-container');
    container.innerHTML = `
        <div class="error-container" style="text-align: center; padding: 40px;">
            <div style="font-size: 4rem; margin-bottom: 20px;">😔</div>
            <h2 style="color: #e53e3e; margin-bottom: 15px;">出现了一些问题</h2>
            <p style="color: #666; margin-bottom: 30px; font-size: 1.1rem;">${message}</p>
            <button onclick="goBack()" class="back-btn" style="max-width: 200px;">返回首页</button>
        </div>
    `;
    
    if (redirectToHome) {
        // 5秒后自动跳转
        setTimeout(() => {
            goBack();
        }, 5000);
    }
}

// 返回首页
function goBack() {
    // 清除存储的结果数据
    localStorage.removeItem('fortuneResult');
    
    // 使用平滑过渡效果
    document.body.style.opacity = '0';
    document.body.style.transition = 'opacity 0.3s ease';
    
    setTimeout(() => {
        window.location.href = 'index.html';
    }, 300);
}

// 分享功能（可选）
function shareResult() {
    if (navigator.share) {
        const fortuneData = JSON.parse(localStorage.getItem('fortuneResult') || '{}');
        navigator.share({
            title: '我的算命结果',
            text: `我是${fortuneData.zodiac}座的${fortuneData.constellation}，今日运势：${fortuneData.fortune?.today?.substring(0, 50)}...`,
            url: window.location.href
        }).catch(console.error);
    } else {
        // 复制到剪贴板
        const fortuneData = JSON.parse(localStorage.getItem('fortuneResult') || '{}');
        const shareText = `我的算命结果：${fortuneData.zodiac} | ${fortuneData.constellation}\n幸运数字：${fortuneData.fortune?.luckyNumber}\n幸运颜色：${fortuneData.fortune?.luckyColor}`;
        
        if (navigator.clipboard) {
            navigator.clipboard.writeText(shareText).then(() => {
                showToast('结果已复制到剪贴板');
            });
        }
    }
}

// 显示提示消息
function showToast(message) {
    const toast = document.createElement('div');
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: #4caf50;
        color: white;
        padding: 12px 24px;
        border-radius: 25px;
        z-index: 1000;
        font-size: 14px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    `;
    
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.remove();
    }, 3000);
}